package tv_megazineplus
import pt.sapo.services.metadata.epg.Channel
import pt.sapo.services.metadata.epg.EPG
import pt.sapo.services.metadata.epg.EPGSoap
import pt.sapo.services.metadata.epg.Program
import java.text.SimpleDateFormat
import org.codehaus.groovy.runtime.TimeCategory
import groovy.time.TimeDuration
import fb.FbUtil
import groovy.sql.Sql

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.soap.DetailEntry;
import javax.xml.ws.soap.SOAPFaultException;

import org.w3c.dom.Node;

import pt.sapo.services.definitions.ESBCredentials;
import pt.sapo.services.metadata.contract.mobile.sms.SMSService;
import pt.sapo.services.metadata.contract.mobile.sms.SMSSoapSecure;

class TesteController {
    def SendMailService
    def SendSmsService
    def FacebookService
    def LoadEAPService
    
    def verify = {
        def user = Users.get(session.user)
        def username = '<b><u>' + user.username + '</u></b>'
        
        [userx: username]
    }
    
    def ramdom (nnn){
        def num = 10 * nnn
        Random random = new Random()
        random.nextInt(10 * num)
    }
    
    def phone = {
       
       def phone = Users.get(session.user).phoneNumber
       def sms = 'In order to confirm your phone, you must introduce this code: '
       def ramdomNumber = ramdom(8)
       
       
       if(SendSmsService.serviceMethod("TvMagP", phone, sms + ramdomNumber))
        {
        use(TimeCategory){ 
       new Token(tipo: 'sms', user: Users.get(session.user), token: ramdomNumber, expira: new Date() + 30.minutes ).save()
       }
    }
    }
    
    def email = {
       def email = Users.get(session.user).email
       def saveP = params.saveP
       
       def sms = 'In order to confirm your phone, you must introduce this code: '
       def ramdomNumber = ramdom(8)       
       
       if(SendMailService.serviceMethod(email, 'Confirm your email!', sms + ramdomNumber)){
       use(TimeCategory){ 
       new Token(tipo: 'email', user: Users.get(session.user), token: ramdomNumber, expira: new Date() + 30.minutes).save()
                         }
       }
       [saveP: saveP]
    }
    
    def errP = {
        
    }
    def errM = {
        
    }
    
    def checkEmail = {
        def code = params.email
        def user = Users.get(session.user)
        def agora = new Date()
        def saveP = params.saveP
        
        def rCode = Token.findWhere(user: user, token: code, tipo: 'email')
                
            if(rCode && agora.before(rCode.expira)){
            
                def vv = UserPrefs.findByUser(user)
                vv.emailVerified = true
                vv.save()
                
                
                
                redirect(action: 'sucessV', params:[thing:"email address", saveP: saveP])
            }else{
                redirect(action: 'errM')
                return
            }
            }
            
     def checkPhone = {
        def code = params.phone
        def user = Users.get(session.user)
        def agora = new Date()
        def saveP = params.saveP
        
        def rCode = Token.findWhere(user: user, token: code, tipo: 'sms')
                
            if(rCode && agora.before(rCode.expira)){
            
                def vv = UserPrefs.findByUser(user)
                vv.phoneVerified = true
                vv.save()
            //chain(action:"sucessV", params:[thing:"mobile phone"])  
            
            redirect(action: 'sucessV', params:[thing:"mobile phone", saveP: saveP])
            }else{
                redirect(action: 'errP')
                return
            }
            }
     def sucessV = {
              [saveP: session.prog.id]
         
     }
    
    def loadChannelsAndProg = {
        
        LoadEAPService.serviceMethod()
    }
    
    def index = {
        redirect(action:'startPage')
    }
    

    
    def myProgramms_canais = {
        
        /*def today = new Date()
        def canal = Channel2.findByChannel_name("RTP 1")
        def prog2 = findByProg_Channel(canal.getID())
        def temp2 = prog2.prog_start.parse("yyyy-MM-dd")
        
        if(today != temp2)
        index()*/
        
        def temp        
        def progs = [:]
        def os
        
        if(params.offset == '')
            os = 0
        else
        os = params.offset
        
        def channel2 = Channel2.list(max:3, offset: os)
        //def prog = Programmation.list()
        
        channel2.each{
            
            temp = Programmation.findAllByProg_channelAndProg_startBetween(it , new Date(), new Date() + 1)
            progs.put(it.id, temp)
        }
        
        def user = Users.get(session.user)
        def username = '<b><u>' + user.username + '</u></b>'
                
        [channel: channel2, program: progs, par:params, cc: Channel2.count(), userx: username]
        
    }
    

    
    def startPage = {
        
    }
    
    def profile = {
        def user = Users.get(session.user)
        def username = '<b><u>' + user.username + '</u></b>'
        def fb = UserPrefs.findByUser(user)
        def rp
        
        if(fb.postMural == false)
        rp = 'não'
        if(fb.postMural == true)
        rp = 'sim'
        [user: Users.get(session.user), userx: username, fb: rp]
    }
    
    def editProfile = {
        def pp = UserPrefs.findByUser(Users.get(session.user))
        
        [userInstance: Users.get(session.user), fb: pp]
    }
    
    def saveProfile = {
        def userInstance = Users.get(session.user)   // create new @user instance to start saving
        
        
                
        def pw = params.hashPassword    // needed to verify if the @password field is empty
        def pw2 = params.hashPassword2
        def aaa = userInstance.hashPassword
        userInstance.username = params.username // @username SET
        //userInstance.hashPassword = params.hashPassword.encodeAsMD5()   // @password enconded to MD5 then SET

        if(params.hashAnswer.size() != 0)
        {   // if the @secretAnswer field is empty, nothing is saved. (Needed in order
            // for the 'secretAnswer.empty.error' work

            userInstance.hashAnswer = params.hashAnswer.encodeAsMD5()
        }else{
            userInstance.hashAnswer = ''
        }
        
        if(params.hashPassword.size() != 0)
        {   // if the @secretAnswer field is empty, nothing is saved. (Needed in order
            // for the 'secretAnswer.empty.error' work

            
        }else{
            userInstance.hashPassword = ''
            pw = ''
        }

        def sq = SecretQuestion.get(params.secretQuestion.id) // get the @secretAnswer object with the SETTED ID
        userInstance.secretQuestion = sq    // @secretQuestion SET
        

        userInstance.name = params.name     // @name SET
        
        userInstance.phoneNumber     // @nrC SET
        
        userInstance.email = params.email       // @email SET
        def pp = UserPrefs.findByUser(Users.get(session.user))
        
        if(!pw.equals(pw2)){        // Not empty validation
            flash.message = "Password doesn't match"      // error displaying
            render(view: "editProfile", model: [userInstance: userInstance, fb:pp])
            return false// rendering same view with previous introduced values
        }
        
        if(pw == ""){        // Not empty validation
            flash.message = "Password doesn't match"      // error displaying
            render(view: "editProfile", model: [userInstance: userInstance, fb:pp])   // rendering same view with previous introduced values
            return false
        }
        
        if(pw2 == ""){        // Not empty validation
            flash.message = "Password doesn't match"      // error displaying
            render(view: "editProfile", model: [userInstance: userInstance, fb:pp])   // rendering same view with previous introduced values
            return false
        }
       
        
        if(pw.size() < 4 || pw.size() > 20 || ! pw.matches("[a-zA-z0-9]+")){
            flash.message = "Password must be between [4-20] characters!"
            render(view: "editProfile", model: [userInstance: userInstance, fb:pp])
            return false
        }        
        
            userInstance.hashPassword = params.hashPassword.encodeAsMD5()
         
        def check = UserPrefs.findByUser(Users.get(session.user))
        
        if(params.fb){
                check.postMural = true
            }
            if(!params.fb){
                check.postMural = false
            }
        
        if (userInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'user.label', default: 'Users'), userInstance.id])}"
            check.save()
            redirect(action: "myProgramms_main")
        }
        else {
            render(view: "editProfile", model: [userInstance: userInstance, fb:pp])
        }
    }
    
    def myProgramms_main = {
        def user = Users.get(session.user)
        def username = '<b><u>' + user.username + '</u></b>'
        [userx: username]
    }
    


    def saveAlert = {
        //params.prog // prog object
        
        
      /*Programmation program
        String personalMessage
        Date horaDispara
        String tipo*/
        def saveP= Programmation.get(params.prog)
        def hora = saveP.prog_start
        def user = Users.get(session.user)
        def temp = UserPrefs.findWhere(user: user)
        
        if(params.tipo == 'email'){
            
        if(temp && temp.emailVerified == false){
            redirect(action: 'verifyE', params:[saveP: saveP.id])
        }
        }else{  //sms
            if(temp && temp.phoneVerified == false){
            session.prog = saveP    
            redirect(action: 'verifyP', params:[saveP: saveP.id])
        }
    }
        
        use(TimeCategory){
            
           if(params.quantoAntes == '5m') 
                hora = hora - 5.minutes

           if(params.quantoAntes == '30m') 
                hora = hora - 30.minutes
           
            if(params.quantoAntes == '1h') 
                hora = hora - 1.hours
           
            if(params.quantoAntes == '2h') 
                hora = hora - 2.hours
          
        }
        
        def prog = Programmation.get(params.prog)
        def alert =Alert.findByProgramAndUser(prog, user)
        if(alert)
            alert.delete()
        new Alert(user: user, program: prog, personalMessage: params.message, horaDispara: hora, tipo: params.tipo, sent: 0).save()
        
        
        redirect(action: 'myProgramms_alertas')
    }
    
    def verifyE = {
        def saveP = params.saveP
        [saveP: saveP]
    }
    
    def verifyP = {
        def saveP = params.saveP
        [saveP: saveP]
    }
    
    def saveAlertEdit = {
        //params.prog // prog object
        def alertID = params.alertId
        params.quantoAntes
        def t = params.tipo
        def s = params.message
                
        def alerta = Alert.get(alertID)
        def hora = alerta.program.prog_start
        
        alerta.personalMessage = s
        alerta.tipo = t
                
        use(TimeCategory){
            
           if(params.quantoAntes == '5m') 
                hora = hora - 5.minutes

           if(params.quantoAntes == '30m') 
                hora = hora - 30.minutes
           
            if(params.quantoAntes == '1h') 
                hora = hora - 1.hours
           
            if(params.quantoAntes == '2h') 
                hora = hora - 2.hours          
        }
        alerta.horaDispara = hora
        alerta.save()
        
        redirect(action: 'myProgramms_alertas')
    }
    
    def myProgramms_alertas = {
        def user = Users.get(session.user)
        
        def alerta = Alert.findAllByUser(user)
        
        def username = '<b><u>' + user.username + '</u></b>'
        
        
        [alerta: alerta, userx:username]
    }
    
     def alert = {
         def user = Users.get(session.user)
        def username = '<b><u>' + user.username + '</u></b>'
        
        [alert: Programmation.get(params.prog), userx: username]
    }
    
    def editAlert = {
        def alerta = Alert.get(params.temp)
        render(view: "editAlert", model: [alert: alerta])
    }
    
    def removeAlert = {
        def alerta = Alert.get(params.temp)
        alerta.delete()
        redirect(action: "myProgramms_alertas", alert: Programmation.get(params.prog))
    }
    
   
    // dest, sms
    
    def teste2={
    
        def temp = Programmation.get(197)
                    
        
        [aa: temp.prog_duration]
    }
    
    def teste3 = {
        def userStats = []
        def textoS
        def email = Users.get(5559).email
        def dtInicio, dtFim
        
        use(TimeCategory){
        dtInicio = new Date() - 1.months
        dtFim = new Date() + 1.days
        }
        
        def sql = Sql.newInstance( 'jdbc:postgresql://localhost:5432/ad', 'postgres',
                       'postgres', 'org.postgresql.Driver' )
        sql.eachRow('select count(prog_title) contagem, prog_title,users.email from programmation join alert on programmation.id = alert.program_id join users on alert.user_id = users.id where users.email=\''+email+'\' and alert.hora_dispara between \''+dtInicio+'\' and \''+dtFim+'\' group by alert.user_id, prog_title,email order by contagem desc limit 10 ') {
           userStats.add(new UserStats(program_title:it.prog_title,user_email:it.email,frequencia:it.contagem))
        }
        if(userStats == null){
            
        }else{
            textoS = 'TvMEGAzineP Top ' + userStats.size() + ' Programms:\n\n'
            
            userStats.each{ us ->
                textoS = textoS + '\t\t\t\t - ' + us.program_title + '\n'
            }
        }
       FbUtil fb = new FbUtil()        
                
                    fb.sendComent(Users.get(5559).fbtoken, textoS)
                
    }
    

    
    	def printException(String op, SOAPFaultException e) {
		System.out.println();
		System.out.println(op);
		System.out.println("\tfault: " + e.getFault().getFaultString());

		Node entry = ((DetailEntry) e.getFault().getDetail().getDetailEntries()
				.next()).getFirstChild();

		while (entry != null) {
			System.out.println("\t" + entry.getLocalName() + ": "
					+ entry.getTextContent());
			entry = entry.getNextSibling();
		}
	}
    
    def aha = {
       def date1 = new Date()
       def date2
       def result
       
        use(TimeCategory){
          date2 = date1 + 4.hours
        
        
        result = (date2-date1).seconds
        }
        
   [ result: result.toInteger()]
    }
    
    def login = {

    }

    def handleLogin ={
        def user = Users.findByUsername(params.username)
        def pw = params.password.encodeAsMD5()

        if (params.username == null) {
            flash.messageLogin = "User cannot be empty"
        }else {
        if (!user) {
            flash.messageLogin = "User " + params.username + " not found"
            redirect(controller: 'teste', action:'startPage')
            return
        }else{
            if (user.hashPassword != pw) {
                flash.messageLogin = "Wrong password for user: " + params.username
                redirect(controller: 'teste',action:'startPage')
                return
            }
            else{
                def aha = user.id
                session.user = aha
            }
        }
        }

        redirect(controller: 'teste', action: "myProgramms_main")
    }

    def logout = {
        if(session.user) {
            session.user = null
            redirect(controller: 'teste', action: 'startPage')
        }
        
    }
    
    def registration = {    }

        // con: controller: conference/registration
    def saveUser = {

        
        def userInstance = new Users()   // create new @user instance to start saving
        def pw = params.hashPassword    // needed to verify if the @password field is empty
        def pw2 = params.hashPassword2
        
        userInstance.username = params.username // @username SET
        userInstance.hashPassword = params.hashPassword.encodeAsMD5()   // @password enconded to MD5 then SET

        if(params.hashAnswer.size() != 0)
        {   // if the @secretAnswer field is empty, nothing is saved. (Needed in order
            // for the 'secretAnswer.empty.error' work

            userInstance.hashAnswer = params.hashAnswer.encodeAsMD5()
        }

        def sq = SecretQuestion.get(params.secretQuestion.id) // get the @secretAnswer object with the SETTED ID
        userInstance.secretQuestion = sq    // @secretQuestion SET
        

        userInstance.name = params.name     // @name SET
        userInstance.phoneNumber = params.phoneNumber     // @nrC SET
        userInstance.email = params.email       // @email SET
        
        if(pw != "" && pw2 != "" && pw != pw2){        // Not empty validation
            flash.message = "Password cannot be empty / Password doesn't match"      // error displaying
            render(view: "registration", model: [userInstance: userInstance])   // rendering same view with previous introduced values
        }

        if(pw.size() < 4 || pw.size() > 20 || ! pw.matches("[a-zA-z0-9]+")){
            flash.message = "Password must be between [4-20] characters!"
            render(view: "registration", model: [userInstance: userInstance])
        }
        
        FbUtil fb = new FbUtil()
        String tk
        if(params.fbtoken){
            
        try{
        tk = fb.getTokenByCode(params.fbtoken)
        userInstance.fbtoken = tk
        }catch(Exception e){
            
        }
        
    }else{
            
        }
        
        if (userInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])}"

            new UserPrefs(emailVerified: false, phoneVerified: false, postMural: false, user: userInstance).save(failOnError: true)            
            redirect(action: "myProgramms_main")
        }
        else {
            render(view: "registration", model: [userInstance: userInstance])
        }
        
    }
    

}